define(['js/resolve'], function(resolve) {
    angular.module('app.winresize', [])
        .directive('winresize', winResizeDirective);

    function winResizeDirective($timeout) {
        return resolve({
            restrict: 'E',
            replace: true,
            template: '<button type="button" class="resize" ng-click="resize()">'
                    + '  <i class="fa" ng-class="{\'fa-window-maximize\': !fullscreen, \'fa-window-restore\': fullscreen}"></i>'
                    + '</button>',
            scope: {
                onChanged: '<'
            },
            link: function(scope, element) {
                scope.fullscreen = false;
                scope.resize = function() {
                    element.blur();
                    scope.fullscreen = !scope.fullscreen;
                    element.parents('.modal-dialog').toggleClass('fullscreen');
                    resizeModelCallback();
                }

                jQuery(window).bind('resize', resizeModelCallback);
                scope.$on('$destroy', function() {
                    jQuery(window).unbind('resize', resizeModelCallback);
                });

                function resizeModelCallback() {
                    $timeout(function() {
                        resizeModal(scope.onChanged);
                    });
                }

                function resizeModal(callback) {
                    var dialog = element.parents('.modal-dialog');
                    //
                    var headerHeight = dialog.find('.modal-header').outerHeight() || 0;
                    var footerHeight = dialog.find('.modal-footer').outerHeight() || 0;
                    //
                    var bodyWidth = dialog.find('.modal-body').width(),
                        bodyHeight = dialog.height() - headerHeight - footerHeight;

                    if (scope.fullscreen) {
                        dialog.find('.modal-body').css('height', bodyHeight + 'px');
                    } else {
                        dialog.find('.modal-body').css('height', '');
                    }

                    if (typeof(callback) === 'function') {
                        callback(bodyHeight, bodyWidth, scope.fullscreen);
                    }
                }
            }
        });
    }
});
